<?php
namespace Api\Controller;
use Think\Controller;
class TakeOutController extends CommonController {
    //获取轮播图列表
    public function getAdList(){
        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        $result = M('takeout_ad')
            ->where($map)
            ->select();

        return $this->ajaxReturn($result);
    }
    //获取店铺类型列表
    public function getShopTypeList(){
        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        $result = M('takeout_shoptype')
            ->where($map)
            ->select();
        return $this->ajaxReturn($result);
    }
    //获取店铺列表
    public function getStoreList(){
        $wid = session('wid');
        $lat = $_POST['lat'];
        $lng = $_POST['lng'];
        $where=" WHERE wid=".$wid." and is_open=1";
        $pageindex = max(1,intval($_POST['page']));
        $pagesize = $_POST['pagesize'];
        $sql="SELECT *, ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-SUBSTRING_INDEX(coordinates, ',', 1)*PI()/180)/2),2)+COS($lat*PI()/180)*COS(SUBSTRING_INDEX(coordinates, ',', 1)*PI()/180)*POW(SIN(($lng*PI()/180-SUBSTRING_INDEX(coordinates, ',', -1)*PI()/180)/2),2)))*1000) AS juli  
     FROM tp_takeout_store".$where ." ORDER BY juli ASC";
        $select_sql =$sql." LIMIT " .($pageindex - 1) * $pagesize.",".$pagesize;
        $result = M()->query($select_sql);
        $this->ajaxReturn($result);
    }
    //获取店铺信息
    public function getStoreInfo(){
        $member = M('member')
            ->where(array('openid'=>$_POST['openid']))
            ->getField('mid');
        if($member['id']){
            $data = array();
            $data['user_id']=$member['mid'];
            $data['store_id']=$_POST['id'];
            $data['time']=date("Y-m-d");
            $list = M('takeout_traffic')
                ->where($data)
                ->find();
            if(!$list){
              M('takeout_traffic')
                  ->add($data);
            }
        }
          

        // $res=pdo_get('wpdc_store',array('uniacid'=>$_W['uniacid'],'id'=>$_POST['id']));
        $map = array();
        $map['wid'] = session('wid');
        $map['id'] = $_POST['id'];
        $res = M('takeout_store')
            ->where($map)
            ->find();
        if($res['img']){
            if(strlen($res['img'])>51){
              $res['img']= explode(',',$res['img']);
            }else{
              $res['img']=array(
                0=>$res['img']
                );
            }  
        }
        if($res['yyzz']){
           if(strlen($res['yyzz'])>51){
            $res['yyzz']= explode(',',$res['yyzz']);
          }else{
            $res['yyzz']=array(
              0=>$res['yyzz']
              );
          }
        }
        if($res['environment']){
            if(strlen($res['environment'])>51){
              $res['environment']= explode(',',$res['environment']);
            }else{
              $res['environment']=array(
                0=>$res['environment']
                );
            }
        }
        $res['store_video'] = $this->video($res['store_video']);

        $this->ajaxReturn($res);
    }
    function video($video){
        $vid=trim(strrchr($video, '/'),'/');
        $vid=substr($vid,0,-5);
        $json=file_get_contents("http://vv.video.qq.com/getinfo?vids=".$vid."&platform=101001&charge=0&otype=json");
       // echo $json;die;
        $json=substr($json,13);
        $json=substr($json,0,-1);
        $a=json_decode(html_entity_decode($json));
        $sz=json_decode(json_encode($a),true);
       // print_R($sz);die;
        $url=$sz['vl']['vi']['0']['ul']['ui']['3']['url'];
        $fn=$sz['vl']['vi']['0']['fn'];
        $fvkey=$sz['vl']['vi']['0']['fvkey'];
        $url=$url.$fn.'?vkey='.$fvkey;
        return  $url;
    }
    //获取商家减满列表
    public function getReductionList(){
        $result = M('takeout_reduction')
            ->where(array('store_id'=>$_POST['id']))
            ->select();
        $this->ajaxReturn($result);
    }

    //商家二维码
    public function getStoreCode(){ 
        $base64_image_content="data:image/jpeg;base64,".$this->getCoade($_POST['store_id']);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = "../xiaochengxu/images/storecode/";
            if(!file_exists($new_file))
            {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0777);
            }
            $wname="{$_POST['store_id']}".".{$type}";
            //$wname="1511.jpeg";
            $new_file = $new_file.$wname;
            if(!file_exists($new_file)){
                file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));
            }
            
        }
        echo "../../../images/storecode/".$wname;
    }
    function  getCoade($storeid){
       $img=$this->set_msg($storeid);
       $img=base64_encode($img);
       return $img;
    }
    function set_msg($storeid){
        $access_token = $this->getaccess_token();
        $data2=array(
            "scene"=>$storeid,
            "page"=>"pages/index/takeout/info",
            "width"=>400
        );
        $data2 = json_encode($data2);
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token."";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data2);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    function getaccess_token(){
        $wid = session('wid');
        $res = M('wechat')
            ->where(array('id'=>$wid))
            ->find();
        $appid=$res['appid'];
        $secret=$res['app_secret'];
          // print_r($res);die;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['access_token'];
    }
    //获取座位信息列表
    public function getTableType(){
     $wid = session('wid');
     $map = array();
     $map['wid'] = $wid;
     $map['seller_id'] = $_POST['store_id'];
     $result = M('takeout_table_type')
         ->where($map)
         ->select();
     $this->ajaxReturn($result);
   }
   //预定
    public function Reservation(){
        $wid = session('wid');
        $user_id = $this->getMemberId($_POST['openid']);
        $table_type_info = $this->getTableTypeInfo($_POST['table_type_id']);

        $data['store_id']=$_POST['store_id'];//商家id
        $data['user_id']=$user_id;//用户id
        $data['xz_date']=$_POST['xz_date'];//选择日期
        $data['yjdd_date']=$_POST['yjdd_date'];//预计到店时间
        $data['table_type_id']=$_POST['table_type_id'];//桌位类型ID
        $data['link_name']=$_POST['link_name'];//联系人
        $data['link_tel']=$_POST['link_tel'];//联系电话
        $data['jc_num']=$_POST['jc_num'];//就餐人数
        $data['remark']=$_POST['remark'];//备注
        $data['pay_money']=$_POST['money'];//付款金额
        $data['ydcode']=$_POST['ydcode'];//
        $data['order_num']=date('YmdHis',time()).rand(1111,9999);//订单号
        $data['table_type_name']=$table_type_info['name'];//桌台类型名称
        $data['zd_cost']=$table_type_info['zd_cost'];//桌台类型最低消费
        $data['state']=0;//待支付
        $data['del']=2;//未删除
        $data['wid']=$wid;//小程序id
        $data['created_time']=date('Y-m-d H:i:s');//下单时间
        $data['time2']=time();//下单时间搓
        $data['is_yue']=$_POST['is_yue'];//支付类型
        $data['is_pay'] = 0;
        $res = M('takeout_ydorder')
            ->add($data);
        $order_id=$res;
        if($res){
            $sdata = array();
            $sdata['state'] = 1;
            M('takeout_ydorder')
                ->where(array('id'=>$order_id))
                ->save($sdata);

            echo $order_id;
        }else{
            echo '预定失败';
        }
    }
    //获取用户id
    public function getMemberId($openid){
        $id = M('member')
            ->where(array('openid'=>$openid))
            ->getField('mid');
        return $id;
    }
    //获取座位类型信息
    public function getTableTypeInfo($id){
        $table_type_info = M('takeout_table_type')
            ->where(array('id'=>$id))
            ->find();
        return $table_type_info;
    }
    //预订付款
    public function reservePay(){

        $map = array();
        $map['wid'] = session('wid');
        $wechat = M("Wechat")
            ->where($map)
            ->find();

        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $title = "预订订单付款";
        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/reserveOrder");
        // echo $url;
        $out_trade_no = $this->build_order_no();
        $data = array();
        $data['ydcode'] = $out_trade_no;
        M('takeout_ydorder')
            ->where(array('id'=>$_POST['order_id']))
            ->save($data);

        $result = $this->doWechatPay($title,$out_trade_no,$_POST['money'],$url,$_POST['openid'],$appid,$mch_id,$key);
        $this->ajaxReturn($result);
    }
    //获取预订信息
    public function getReservationInfo(){
        $result = M('takeout_ydorder')
            ->alias('y')
            ->join('tp_takeout_store s ON s.id=y.store_id')
            ->where(array('y.id'=>$_POST['id']))
            ->field('y.*,s.tel,s.logo')
            ->find();
//        $sql="select a.* ,b.name,b.tel,b.logo from " . tablename("wpdc_ydorder") . " a"  . " left join " . tablename("wpdc_store") . " b on b.id=a.store_id   WHERE a.id=:id ";
//        $list=pdo_fetch($sql,array(':id'=>$_GPC['id']));
        echo json_encode($result);
    }
    //取消预订
    public function cancelReservation(){
        $data = array();
        $data['state']=4;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //转换坐标
    public function transformCoordinate(){
        $op=$_POST['op'];
        $key = '37BBZ-IASRP-7VZDT-V6FJE-USUFE-OVFGR';
        $url="https://apis.map.qq.com/ws/coord/v1/translate?locations=".$op."&type=3&key=".$key;
        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);
        $this->ajaxReturn(json_decode($output,true));
    }
    //计算店铺评分
    public function calculateScore(){
        $wid = session('wid');
        $map = array();
        $map['wid'] = $wid;
        $map['seller_id'] = $_POST['seller_id'];
        $total = M('takeout_access')
            ->where($map)
            ->sum('score');
        $count = M('takeout_access')
            ->where($map)
            ->count('id');
        if($total['total']>0 and $count['count']>0){
            echo ($total['total']/$count['count']);
        }else{
            echo '0';
        }
    }
    //获取店铺评论
    public function getStorePl(){
        $list = M('takeout_access')
            ->alias('a')
            ->join('tp_member m ON m.mid=a.user_id','LEFT')
            ->where(array('a.seller_id'=>$_POST['id']))
            ->select();
        $this->ajaxReturn($list);
    }
    //获取外卖菜品列表
    public function getDishesList()
    {

        $wid = session('wid');

        $map = array();
        $map['wid'] = $wid;
        $map['store_id'] = $_POST['id'];
        $map['is_open'] = 1;
        $type = M('takeout_type')
            ->where($map)
            ->order("order_by ASC")
            ->select();

        $lmap = array();
        $lmap['wid'] = $wid;
        $lmap['is_shelves'] = 1;
        $lmap['dishes_type'] = array('neq',$_POST['dishes_type']);
        $lmap['store_id'] = $_POST['id'];
        $list = M('takeout_dishes')
            ->where($lmap)
            ->order("sorting ASC")
            ->select();
        $data2=array();
        for($i=0;$i<count($type);$i++){
            $data=array();
            for($k=0;$k<count($list);$k++){
                if($type[$i]['id']==$list[$k]['type_id']){
                    $data[]=array(
                        'id'=>$list[$k]['id'],
                        'name'=>$list[$k]['name'],
                        'img'=>$list[$k]['img'],
                        'num'=>$list[$k]['num'],
                        'money'=>$list[$k]['money'],
                        'one'=>$list[$k]['one'],
                        'signature'=>$list[$k]['signature'],
                        'dishes_type'=>$list[$k]['dishes_type'],
                        'xs_num'=>$list[$k]['xs_num'],
                        'sit_ys_num'=>$list[$k]['sit_ys_num'],
                        'wm_money'=>$list[$k]['wm_money'],
                        'details'=>$list[$k]['details'],
                        'box_fee'=>$list[$k]['box_fee']
                    );
                }
            }
            $data2[]=array(
                'id'=>$type[$i]['id'],
                'type_name'=>$type[$i]['type_name'],
                'goods'=>$data
            );
        }
        $this->ajaxReturn($data2);
    }
    //获取外卖菜品信息
    public function getDishesInfo(){
        $res = M('takeout_dishes')
            ->where(array('id'=>$_POST['id']))
            ->find();
        $res2 = M('takeout_spec')
            ->where(array('goods_id'=>$_POST['id']))
            ->select();
        $data['dishes']=$res;
        $data['spec']=$res2;
        echo json_encode($data);
    }
    //获取菜品规格
    public function getDishesGg(){
        $res = M('takeout_spec')
            ->where(array('goods_id'=>$_POST['dishes_id']))
            ->select();
        $this->ajaxReturn($res);
    }
    //更新用户地址信息
    public function upAddress(){
        $data['user_name']=$_POST['user_name'];
        $data['user_tel']=$_POST['user_tel'];
        $data['user_address']=$_POST['user_address'];
        $res = M('member')
            ->where(array('openid'=>$_POST['openid']))
            ->save($data);
        if($res){
            echo '1';
        }else{
            echo '2';
        }
    }
    //获取用户信息
    public function getUserInfo(){
        $res = M('member')->where(array('openid'=>$_POST['openid']))->find();
        $this->ajaxReturn($res);
    }
    //查看是否为外卖新用户
    public function isNew(){
        $user_id = $this->getMemberId($_POST['openid']);
        $map = array();
        $map['user_id'] = $user_id;
        $map['type'] = 1;
        $res = M('takeout_order')
            ->where($map)
            ->find();
        if($res){
            echo  '2';//不是
        }else{
            echo  '1';//是
        }
    }
    //添加订单
    public function addOrder(){
        $wid = session('wid');
        if($_POST['type']==1){//外卖
            $data['user_id']=$_POST['user_id'];
            $data['order_num']=date('YmdHis',time()).rand(1111,9999);

            $data['state']=1;
            $data['time']=date("Y-m-d H:i:s",time());
            $data['time2']=time();
            $data['money']=$_POST['money'];
            $data['preferential']=$_POST['preferential'];
            $data['tel']=$_POST['tel'];
            $data['name']=$_POST['name'];
            $data['note']=$_POST['note'];//备注
            $data['address']=$_POST['address'];
            $data['type']=$_POST['type'];
            $data['area']=$_POST['area'];
            $data['lat']=$_POST['lat'];
            $data['lng']=$_POST['lng'];
            $data['wid']=$wid;//小程序id
            $data['freight']=$_POST['freight'];//配送费
            $data['box_fee']=$_POST['box_fee'];//餐盒费
            $data['coupons_id']=$_POST['coupons_id'];//优惠劵ID
            $data['voucher_id']=$_POST['voucher_id'];//代金劵ID
            $data['seller_id']=$_POST['seller_id'];//商家
            $data['delivery_time']=$_POST['delivery_time'];//送达时间
            $data['is_take']=$_POST['is_take'];//1.自取 2.不自取
            $data['is_yue']=$_POST['is_yue'];//1余额支付  2.微信支付  3.积分支付
            $data['form_id']=$_POST['form_id'];

            $res = M('takeout_order')
                ->add($data);
            $order_id = $res;

            $a=json_decode(html_entity_decode($_POST['sz']));
            $sz=json_decode(json_encode($a),true);
            // print_R($sz);die;

            $data3['state']=1;
            if($_GPC['coupons_id']){
                // echo $_GPC['coupons_id'];die;
                $map = array();
                $map['coupons_id'] = $_POST['coupons_id'];
                $map['user_id'] = $_POST['user_id'];
                M('takeout_usercoupons')
                    ->where($map)
                    ->save($data3);
            }
            if($_GPC['voucher_id']){
                $vmap = array();
                $vmap['voucher_id'] = $_POST['voucher_id'];
                $vmap['user_id'] = $_POST['user_id'];
                M('takeout_uservoucher')
                    ->where($vmap)
                    ->save($data3);
                //  echo $_GPC['voucher_id'];die;
            }
            if($res){
                for($i=0;$i<count($sz);$i++){
                    $data2['name']=$sz[$i]['name'];
                    $data2['number']=$sz[$i]['num'];
                    $data2['money']=$sz[$i]['money'];
                    $data2['img']=$sz[$i]['img'];
                    $data2['dishes_id']=$sz[$i]['dishes_id'];
                    $data2['wid']=$wid;//小程序id
                    $data2['order_id']=$order_id;
                    $res2 = M('takeout_goods')
                        ->add($data2);
                }
                echo $order_id;
            }else{
                echo '下单失败';
            }
        }elseif($_POST['type']==2){//店内
            $data['preferential']=$_POST['preferential'];
            $data['user_id']=$_POST['user_id'];
            $data['order_num']=date('YmdHis',time()).rand(1111,9999);
            $data['time']=date("Y-m-d H:i:s",time());
            $data['time2']=time();
            $data['note']=$_POST['note'];//备注
            $data['money']=$_POST['money'];
            $data['type']=$_POST['type'];
            $data['dn_state']=1;
            $data['wid']=$wid;//小程序id
            $data['table_id']=$_POST['table_id'];//桌号
            $data['coupons_id']=$_POST['coupons_id'];//优惠劵ID
            $data['voucher_id']=$_POST['voucher_id'];//代金劵ID
            $data['seller_id']=$_POST['seller_id'];//商家
            $data['is_yue']=$_POST['is_yue'];//1是  2.不是
            $data['form_id']=$_POST['form_id'];
            $res = M('takeout_order')
                ->add($data);
            $order_id=$res;
            $a=json_decode(html_entity_decode($_POST['sz']));
            $sz=json_decode(json_encode($a),true);
            $data3['state']=1;
            if($_GPC['coupons_id']){
                M('takeout_usercoupons')
                    ->where(array('coupons_id'=>$_POST['coupons_id']))
                    ->save($data3);
            }
            if($_GPC['voucher_id']){
                M('takeout_uservoucher')
                    ->where(array('vouchers_id'=>$_POST['voucher_id']))
                    ->save($data3);
            }
            if($res){
                M('takeout_table')
                    ->where(array('id'=>$_POST['table_id']))
                    ->save(array('status'=>2));
                for($i=0;$i<count($sz);$i++){
                    $data2['name']=$sz[$i]['name'];
                    $data2['number']=$sz[$i]['num'];
                    $data2['money']=$sz[$i]['money'];
                    $data2['img']=$sz[$i]['img'];
                    $data2['dishes_id']=$sz[$i]['dishes_id'];
                    $data2['wid']=$wid;//小程序id
                    $data2['order_id']=$order_id;
                    $res2 = M('takeout_goods')
                        ->add($data2);
                }
                echo $order_id;
            }else{
                echo '下单失败';
            }
        }
    }
    //外卖付款
    public function takeoutPay(){
        $map = array();
        $map['wid'] = session('wid');
        $wechat = M("Wechat")
            ->where($map)
            ->find();

        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $title = "外卖订单付款";
        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/takeoutOrder");
        // echo $url;
        $out_trade_no = $this->build_order_no();
        $data = array();
        $data['sh_ordernum'] = $out_trade_no;
        M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save($data);

        $result = $this->doWechatPay($title,$out_trade_no,$_POST['money'],$url,$_POST['openid'],$appid,$mch_id,$key);
        $this->ajaxReturn($result);
    }
    //进行微信支付
    public function doWechatPay($title,$out_trade_no,$money,$url,$openid,$appid,$mch_id,$key){
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($title);
        $input->SetAttach($title);
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee(($money*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        return json_decode($jsApiParameters,true);
    }
    //获取优惠券列表
    public function getCouponsList(){
        $wid = session('wid');
        $openid = $_POST['openid'];
        $userid = $this->getMemberId($openid);
        $list = M('takeout_usercoupons')
            ->alias("a")
            ->join("tp_takeout_coupons b ON b.id=a.coupons_id","LEFT")
            ->join("tp_takeout_store c ON c.id=b.store_id","LEFT")
            ->where(array("a.user_id"=>$userid))
            ->field("a.* ,b.name,b.start_time,b.end_time,b.conditions,b.preferential,b.coupons_type,b.instruction,c.name as store_name,c.id as store_id")
            ->select();
        $res = M("takeout_coupons")
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.store_id","LEFT")
            ->where(array('a.wid'=>$wid))
            ->field("a.* ,b.name as store_name")
            ->select();
        $data['ok']=$list;
        $data['all']=$res;
        $this->ajaxReturn($data);

    }
    //获取代金券列表
    public function getVoucherList(){
        $wid = session("wid");
        $openid = $_POST['openid'];
        $userid = $this->getMemberId($openid);

        $list = M('takeout_uservoucher')
            ->alias('a')
            ->join("tp_takeout_voucher b ON b.id=a.vouchers_id","LEFT")
            ->join("tp_takeout_store c ON c.id=b.store_id","LEFT")
            ->where(array("a.user_id"=>$userid))
            ->field("a.* ,b.name,b.start_time,b.end_time,b.preferential,b.voucher_type,b.instruction,c.name as store_name ,c.id as store_id")
            ->select();

        $res = M("takeout_voucher")
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.store_id","LEFT")
            ->where(array("a.wid"=>$wid))
            ->field("a.* ,b.name as store_name")
            ->select();

        $data['ok']=$list;
        $data['all']=$res;
        $this->ajaxReturn($data);
    }
    //领取代金券
    public function addVoucher(){
        $wid = session("wid");
        $openid = $_POST['openid'];
        $user_id = $this->getMemberId($openid);
        $data = array();
        $data['user_id'] = $user_id;
        $data['vouchers_id']=$_POST['vouchers_id'];
        $data['wid']=$wid;
        $data['state']=2;

        $map = array();
        $map['user_id'] = $user_id;
        $map['vouchers_id'] = $_POST['vouchers_id'];
        $res2 = M('takeout_uservoucher')
            ->where($map)
            ->find();

        if($res2){
            echo  '不能重复领取';
        }else{
            $res = M('takeout_uservoucher')
                ->add($data);
            if($res){
                echo '1';
            }else{
                echo '2';
            }
        }
    }
    //领取优惠券
    public function addCoupons(){
        $wid = session("wid");
        $openid = $_POST['openid'];
        $user_id = $this->getMemberId($openid);
        $data = array();
        $data['user_id'] = $user_id;
        $data['coupons_id'] = $_POST['coupons_id'];
        $data['wid'] = $wid;
        $data['state'] = 2;
        $map = array();
        $map['user_id'] = $user_id;
        $map['coupons_id'] = $_POST['coupons_id'];
        $res2 = M('takeout_usercoupons')
            ->where($map)
            ->find();

        if($res2){
            echo  '不能重复领取';
        }else{
            $res = M('takeout_usercoupons')
                ->add($data);
            if($res){
                echo '1';
            }else{
                echo '2';
            }
        }
    }
    //查看我的预约
    public function getMyReservation(){
        $user_id = $this->getMemberId($_POST['openid']);
        $map = array();
        $map['a.user_id'] = $user_id;
        $map['a.del'] = 2;
        $list = M('takeout_ydorder')
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.store_id","LEFT")
            ->where($map)
            ->field("a.* ,b.name,b.tel,b.logo")
            ->order("a.id DESC")
            ->select();
        $this->ajaxReturn($list);
    }
    //我的订单
    public function getMyorder(){
        $user_id = $this->getMemberId($_POST['openid']);
        $map = array();
        $map['a.user_id'] = $user_id;
        $map['a.del'] = 2;
        $res = M('takeout_order')
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.seller_id","LEFT")
            ->where($map)
            ->field("a.* ,b.logo,b.name as store_name,b.tel as store_tel")
            ->order("a.id DESC")
            ->select();
        // $res=pdo_getall('wpdc_order',array('user_id'=>$user_id), array() , '' , 'id Desc');
        $res2 = M('takeout_goods')
            ->select();
        //  $res3=pdo_get('wpdc_store',array('uniacid'=>$_W['uniacid']));
        $data2=array();
        for($i=0;$i<count($res);$i++){
            $data=array();
            for($k=0;$k<count($res2);$k++){
                if($res[$i]['id']==$res2[$k]['order_id']){
                    $data[]=array(
                        'name'=>$res2[$k]['name'],
                        'num'=>$res2[$k]['number'],
                        'img'=>$res2[$k]['img'],
                        'money'=>$res2[$k]['money'],
                        'dishes_id'=>$res2[$k]['dishes_id']
                    );
                }
            }
            $data2[]=array(
                'id'=>$res[$i]['id'],
                'order_num'=>$res[$i]['order_num'],
                'time'=>$res[$i]['time'],
                'state'=>$res[$i]['state'],
                'dn_state'=>$res[$i]['dn_state'],
                'money'=>$res[$i]['money'],
                'type'=>$res[$i]['type'],
                'tel'=>$res[$i]['store_tel'],
                'goods'=>$data,
                'img'=> $res[$i]['logo'],
                'name'=> $res[$i]['store_name'],
                'is_yue'=> $res[$i]['is_yue']
            );
        }
        $this->ajaxReturn($data2);
    }
    //订单详情
    public function getOrderInfo(){
        $res = M('takeout_order')
            ->alias("a")
            ->join("tp_takeout_table b ON b.id=a.table_id","LEFT")
            ->join("tp_takeout_table_type c ON b.type_id=c.id","LEFT")
            ->where(array("a.id"=>$_POST['id']))
            ->field("a.* ,b.name as table_name ,c.name  as  table_name_type")
            ->find();
        $res2 = M('takeout_goods')
            ->where(array('order_id'=>$_POST['id']))
            ->select();
        $res3 = M('takeout_store')
            ->where(array('id'=>$res['seller_id']))
            ->find();
        $data['order']=$res;
        $data['good']=$res2;
        $data['store']=$res3;
        $this->ajaxReturn($data);
    }
    //取消订单
    public function cancelOrder(){
        $order = M("takeout_order")
            ->where(array('id'=>$_POST['order_id']))
            ->find();
        if($order['type']==1){
            $data['state']=5;
        }elseif($order['type']==2){
            $data['dn_state']=3;
        }
        $data['cancel_time']=time();
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save($data);
        if($res){
            $data3['state']=2;
            if($order['coupons_id']){
                $map = array();
                $map['coupons_id'] = $order['coupons_id'];
                $map['user_id'] = $order['user_id'];
                M('takeout_usercoupons')
                    ->where($map)
                    ->save($data3);
            }
            if($order['voucher_id']){
                $vmap = array();
                $vmap['vouchers_id'] = $order['vouchers_id'];
                $vmap['user_id'] = $order['user_id'];
                M('takeout_uservoucher')
                    ->where($vmap)
                    ->save($data3);
            }
            echo '1';
        }else{
            echo '2';
        }
    }
    //删除订单
    public function delOrder(){
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save(array('del'=>1));
        if($res){
            echo '1';
        }else{
            echo '2';
        }
    }
    //申请退款
    public function refundOrder(){
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save(array('state'=>7));
        if($res){
            echo '1';
        }else{
            echo '2';
        }
    }
    //确认收货
    public function completeOrder(){
        $data = array();
        $data['state']=4;
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo '1';
        }else{
            echo  '2';
        }
    }
    //评论
    public function  comment(){
        $wid = session('wid');
        $data['seller_id']=$_POST['seller_id'];//商家id
        $data['order_id']=$_POST['order_id'];//订单id
        $data['order_num']=$_POST['order_num'];//订单号
        $data['score']=$_POST['score'];//分数
        $data['content']=$_POST['content'];//内容
        $data['img']=$_POST['img'];//图片
        $data['cerated_time']=date("Y-m-d H:i:s",time());//创建时间
        $data['user_id']=$_POST['user_id'];//用户id
        $data['wid']=$wid;//小程序id
        $data['status']=1;//未回复
        $res = M('takeout_access')
            ->add($data);
        $order = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->find();
        if($res){
            $total = M('takeout_access')
                ->where(array('wid'=>2,'seller_id'=>$_POST['seller_id']))
                ->sum('score');
            $count = M('takeout_access')
                ->where(array('wid'=>2,'seller_id'=>$_POST['seller_id']))
                ->count("id");
            if($total['total']>0 and $count['count']>0){
                $pf=($total/$count);
                $pf=number_format($pf,1);
            }else{
                $pf=0;
            }
            M('takeout_store')
                ->where(array('id'=>$_POST['seller_id']))
                ->save(array('score'=>$pf));
            // echo $order['type'];die;
            if($order['type']==1){
                $data2['state']=6;
            }elseif($order['type']==2){
                $data2['dn_state']=4;
            }
            //wpdc_integral
            M('takeout_order')
                ->where(array('id'=>$_POST['order_id']))
                ->save($data2);
            echo '1';
        }else{

            echo '2';

        }

    }
    //申请退款预约
    public function refundReserve(){
        $data = array();
        $data['state']=5;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //取消预约
    public function cancelReserve(){
        $data = array();
        $data['state']=4;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //删除预约
    public function delReserve(){
        $data = array();
        $data['del']=1;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //通过桌号查桌子名称和类型
    public function zhuohao(){
        $res = M('takeout_table')
            ->where(array('id'=>$_POST['id']))
            ->find();
        $res2 = M('takeout_table_type')
            ->where(array('id'=>$res['type_id']))
            ->find();
        $data['table_name']=$res['name'];
        $data['type_name']=$res2['name'];
        $data['status']=$res['status'];
        $this->ajaxReturn($data);
    }
    //座号
    public function getTableList(){
        $wid = session('wid');
        $map = array();
        $map['wid'] = $wid;
        $map['type_id'] = $_POST['type_id'];
        $map['status'] = 0;
        $res = M('takeout_table')
            ->where(array($map))
            ->select();
        $this->ajaxReturn($res);
    }
    //搜索店铺
    public function searchStore(){
        $wid = session('wid');
        $op=$_POST['key'];
        $where = array();
        $where['name|address'] = array('like', "%".$op."%");
        $where['is_open'] = 1;
        $where['wid'] = $wid;

        $list = M('takeout_store')
            ->where(array($where))
            ->select();
        $this->ajaxReturn($list);
    }
}